package com.demo.controller;

import com.demo.domain.User;
import com.demo.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/user/list")
public class UserListController extends HttpServlet {
    private static ObjectMapper mapper = new ObjectMapper();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //转编码格式
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //允许嗅探
        resp.setHeader("Access-Control-Allow-Origin","*");
        resp.setHeader("Access-Control-Allow-Methods","*");
        //创建容器对象
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userService", UserService.class);
        //接收参数
        String currentPage = req.getParameter("currentPage");
        int currentPageInt = Integer.parseInt(currentPage);
        String pageSize = req.getParameter("pageSize");
        int pageSizeInt = Integer.parseInt(pageSize);

        PageInfo<User> pageInfo = userService.list(currentPageInt,pageSizeInt);
        //将查询结果转为JSON串返回给客户端
        mapper.writeValue(resp.getWriter(),pageInfo);
    }
}
